package com.wjjm.spoonselling.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wjjm.spoonselling.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@RestController
public class FileController {
    @Value("${file.folder}")
    private String folder;
    @Value("${file.path}")
    private String path;

//    @PostMapping("/api/commodity/upload-image")
//    public ResponseEntity<Map<String, String>> uploadImage(@RequestBody MultipartFile file) {
//
//        // Save the image to the file system
//        String imageUrl = "/images/" + file.getOriginalFilename();
//        try {
//            Path path = Paths.get("src/main/resources" + imageUrl);
//            Files.copy(file.getInputStream(), path);
//        } catch (IOException e) {
//            return ResponseEntity.badRequest().build();
//        }
//        Map<String, String> response = new HashMap<>();
//        response.put("imageUrl", imageUrl);
//        return ResponseEntity.ok(response);
//    }

    @PostMapping("/api/commodity/upload-image")
    public Result upload(MultipartFile file, HttpServletRequest request) throws Exception {
        String saveName = file.getOriginalFilename();
        if (file.getSize() > 0) {
            IoUtil.copy(file.getInputStream(),
                    FileUtil.getOutputStream(folder + saveName)
            );
        }
        String template = "http://localhost:%s%s/%s";
        String imgUrl = String.format(template, request.getServerPort(), path, saveName);
        JSONObject jsonObject = JSONUtil.createObj().set("src", imgUrl);
        return Result.success(jsonObject);
    }

}
